#include "sac.h"
#include "QDebug"
Sac::Sac()
{
}

Sac::~Sac()
{
}

Sac::Sac(QString fileName)
{
    this->fileName = fileName;
    trace = (Sac_trace *)malloc(sizeof(Sac_trace));
    trace =getTrace();
}

Sac::Sac(QString fileName, DATAFORMAT dataFormat)
{
    this->fileName = fileName;
    trace = (Sac_trace *)malloc(sizeof(Sac_trace));
    trace =getTrace();
}

Sac_trace *Sac::getTrace()
{
    QByteArray ba_input = fileName.toLocal8Bit();
    char *file = ba_input.data();
    FILE *fp = fopen64(file,"rb");
    if(fp!=NULL)
    {
        fseeko64(fp, 0, SEEK_SET);
        fread(trace, sizeof(Sac_trace), 1, fp);
        // fseeko64(fp, 0, SEEK_SET);
        fclose(fp);
        return trace;
    }
    return NULL;
}

QDateTime Sac::getStartTime()
{
    QDateTime dt;
    int year,day,hour,min,sec,msec;
    if(!fileName.isEmpty())
    {
        if(trace==NULL)
            getTrace();
        year = trace->nzyear;
        day = trace->nzjday;
        hour = trace->nzhour;
        min = trace->nzmin;
        sec = trace->nzsec;
        msec =  trace->nzmsec;
        QDate d1=QDate::fromJulianDay((QDate(year,1,1).toJulianDay()+day-1));
        dt=QDateTime(d1,QTime(hour,min,sec,msec));
    }
    return dt;
}
int Sac::getFreq()
{
    if(trace==NULL)
        getTrace();
     return 1000/(int)(trace->delta*1000);
}

int Sac::getInterval()
{
    if(trace==NULL)
        getTrace();
    return (int)(trace->delta*1000);
}

long long Sac::getPointNumber()
{
    LONG length = getFileLength();
    LONG pointNum = (length - 240) / 4;
    return pointNum;
}
int *Sac::getData(LONG start ,LONG end,DATAFORMAT dataformat,int pianyiPoint )
{
    QByteArray ba_input = fileName.toLocal8Bit();
    char *file = ba_input.data();
    FILE *fp = fopen64(file,"rb");
    if(fp!=NULL)
    {
        LONG count = end-start;
        int *data = new int[count+1];
        float *data1 = new float[count+1];
        fseeko64(fp,632+start*4,SEEK_SET);
        fread(data1,sizeof(float),count+1,fp);
        for(int i=0;i<count;i++)
        {
            data[i] = (int)data1[i];
        }
        fclose(fp);
        return data;
    }
    return NULL;
}

